/*==============================================================================
WAGE ESTIMATION ON AGE CUT-OFF

Data 	: B1_age55data.dta.
Folder 	: Jonas/data/B1_age55data.dta
Date	: 2019-11-26

Creator		: Jonas Cederlof	(JC)
Description : 
Notes:


LATEST UPDATE: 	
==============================================================================*/

clear
set more		 off
cap   log close 	_all

log using 	"../log/B2_wages.log"	, replace 
use		 "$datapath/A3_age55data_WC.dta"

{ // Indicate first observations of new job
*===============================================================================
*Condtion on newfirm==1 and observred wage (post eventtime>=0 by construction)
bys lopnr (eventtime_def) : gen nvals = sum(newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid) if newfirmid!=. & manl_newfirm!=. & newfirmid==firstnewfirmid
gen xnvalsdate = date if nvals==1 
bys lopnr (eventtime_def) : egen nvalsdate = max(xnvalsdate) // impute for all obs this value
format nvalsdate %tm

/*
*Generte same as above but correct for observing the wage possibly earlier
bys lopnr (eventtime) : gen nvals2 = sum(1) if firmid_lonestruktur==firstnewfirmid & eventtime_def>=0 & firmid_lonestruktur!=.
gen xnvals2date = date if nvals2==1 
bys lopnr (eventtime_def) : egen nvals2date = max(xnvals2date) // impute for all obs this value
format nvals2date %tm

*Indicate first wage from new firm in wage survey (no matter the firm and RAMS indicators)
bys lopnr (eventtime) : gen nvals4 = sum(1) if firmid!=firmid_lonestruktur & firmid_lonestruktur!=. & eventtime_def>=0
*/


*Pre wage from notifying firm (last observred wage at notifying firm before or at notification)
bys lopnr (eventtime_def) : gen nvals3 = _n if manl!=. & date<=nvalsdate & eventtime_def<=0
bys lopnr (eventtime_def) : egen maxnvals3 = max(nvals3)


*Date for last wage at notifying firm (within 2 yers before notification)
gen xnvals3date = date if nvals3==maxnvals3	& nvals3!=. & inrange(eventtime_def,-24,0)
bys lopnr (eventtime_def) : egen nvals3date = max(xnvals3date)
format nvals3date %tm

*Difference in time between old and new wage
gen diff = nvalsdate - nvals3date
sum diff if nvals==1

*Wage at notifying firm	
gen xprewage = manl if date==nvals3date 
bys lopnr (eventtime_def) : egen prenotfwage = max(xprewage)
drop xprewage

*fixa sa att datumet for gamla lonen inte far vara efter nya jobbet fas (i.e date of nvals3 < date of nvals)

*Generate eventtime for wage growth (i.e time after having found new job)
bys lopnr (eventtime_def) : gen timeafterjob = sum(1) if nvals>=1 & date>= nvalsdate


}
*

*Generate indicator for fiding a job within 24 months after notice
bys lopnr (eventtime_def) : egen within24months = max(nvals==1 & inrange(eventtime_def,0,24))
*keep if within24months==1


{ // Generate wages
*===============================================================================
*Generate log wage variables 
gen log_manl_newfirm = log(manl_newfirm)
bys lopnr (eventtime_def) : gen preobswage= manl_firstnewfirmid[_n-12]!=. & nvals==1 & eventtime_def[_n-12]>=0
bys lopnr (eventtime_def) : replace log_manl_newfirm = log(manl_firstnewfirmid[_n-12]) if preobswage==1
gen diff_log_manl_newfirm = log(manl_newfirm) - log(prenotfwage)
gen log_prenotfwage = log(prenotfwage)


gen manl_newfirm2 = manl_notfirm_specific if firmid_lonest!=firmid
gen log_manl_newfirm2 = log(manl_newfirm2)
gen diff_log_manl_newfirm2 = log(manl_newfirm2) - log(prenotfwage)

*Generate wage growth per year
gen firstnewwage = manl_newfirm if nvals==1
bys lopnr (eventtime_def) : egen fill_manl_newfirm = max(firstnewwage) 
bys lopnr (eventtime_def) : gen wgrowth = log(manl_newfirm) - log(fill_manl_newfirm)


}
*
{ // Save dataset with alla worker having found a job and sampled in wage survey
*===============================================================================
*Save the "wage sample" to be used in other .do-files
preserve
	keep if nvals==1 & eventtime_def<=24
	keep lopnr 
	count
	gen inwagesample = 1
	save "$datapath/wagesample.dta",replace
restore
}
*
{ // Generate EE-transistion indicator
*===============================================================================
forvalues t=0(1)24 {
	local j = `t'-1
	*Indicate transition from notification to a new job without non-employment inbetween (i.e EtoE)
	qui bys lopnr (eventtime_def): egen nonemp`t'= max(atfirm2==0 & working2==0 & otherfirm2==0 ) if  date<=nvalsdate & nvalsdate!=. & inrange(eventtime_def,0,`t')
	qui bys lopnr (eventtime_def) : egen EtoE`t' = max(nonemp`t'==0 & otherfirm2==1) 
	if `t'>0{
		qui replace EtoE`t' = 1 if EtoE`j'==1
	}	
}


qui bys lopnr (eventtime_def) : egen nonemp= max(working2==0) if inrange(date,notdate_def,nvalsdate)

forvalues t=0(1)24 {
	local j = `t'-1
	qui bys lopnr (eventtime_def) : egen xEUE`t' = max(otherfirm2==1 & EtoE`t'==0 & nonemp==1) if   inrange(eventtime_def,0,`t')
	qui bys lopnr (eventtime_def) : egen EUE`t' = max(xEUE`t')
	if `t'>0{
	qui	replace EUE`t' = 1 if EUE`j'==1
	}	
}

*Indicator for having left notifying firm
forvalues t=0(1)24 {
	local j = `t'-1
	qui bys lopnr (eventtime_def) : egen leftfirm`t' = max(atfirm2==0)  if   inrange(eventtime_def,0,`t')
	if `t'>0{
	qui	replace leftfirm`t' = 1 if leftfirm`j'==1
	}	
}


*Fill in data to long format
qui gen EtoE=.
qui gen EUE=.
qui gen leftfirm = . 
forvalues t=0(1)24{	
qui	replace EtoE = EtoE`t' if eventtime_def==`t'  
qui	replace EUE = EUE`t' if eventtime_def==`t'
qui	replace leftfirm = leftfirm`t' if eventtime_def==`t'
}
drop xEUE1-xEUE24 EUE1-EUE24 EtoE1-EtoE24

*Recalls
bys lopnr eventtime_def : gen recall = atfirm2==1 & leftfirm==1
replace recall=0 if EtoE==1 | EUE==1 // Don't allow recalls after having found a new job

*Employment to unemployment
bys lopnr eventtime_def : gen EU = EtoE==0 & EUE==0 & atfirm2==0 & working2==0
}
*
{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "	
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
bys lopnr  : gen eventyear = year(dofm(notdate_def)) 
replace eventyear = year - eventyear

bys lopnr (eventtime) : gen x_firmid_lonestruktur_tm1 = firmid_lonestruktur if eventyear==-1
bys lopnr (eventtime) : egen firmid_lonestruktur_tm1 = max(x_firmid_lonestruktur_tm1)
drop x_firmid_lonestruktur_tm1
bys lopnr (eventtime_def) : gen nvals2 = sum(1) if log_manl_newfirm2!=. & inrange(eventtime_def,0,48)
gen same = firmid_lonestruktur_tm1==firmid_lonestruktur & nvals2==1 & inrange(eventtime_def,0,48)


{ // Table of new wage and wage growth
*===============================================================================
*============
xtset ym_def
*============
preserve
*Note: nvals==1 is what makes it the first wage observation at the first new firm
keep if nvals==1  &  eventtime_def<=24 | nvals2==1 & eventtime_def<=24 

eststo clear
qui eststo: xtreg log_manl_newfirm2			$instrument $linear $covariets  if nvals2==1 , cluster(varselid) fe nonest 
qui eststo: xtreg log_manl_newfirm			$instrument $linear $covariets  if nvals==1 , cluster(varselid) fe nonest 
qui eststo: xtreg diff_log_manl_newfirm  		$instrument $linear $covariets  if nvals==1, cluster(varselid) fe nonest 
qui eststo: xtreg diff_log_manl_newfirm 		$instrument $linear $covariets  if nvals==1 & eventtime_def<=6 & EtoE==1, cluster(varselid) fe nonest 
qui eststo: xtreg EtoE					$instrument $linear $covariets 	if nvals==1 , cluster(varselid) fe nonest 


esttab , keep($instrument   _cons) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) 	
esttab using "$agetablepath/RF/tab_wage_growth.tex", 				/// 
replace keep($instrument  _cons) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(treat "Above age-55" _cons "Control mean" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
title("Wage effect of advance notice")		///
stats( N_clust N, fmt( %9.0fc %9.0fc) 		/// 
labels( "\# clusters" "\# observations")) ///
nonotes  prehead("\begin{table}[htbp]\centering" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{Wage effect of advance notice}" ///
"\begin{tabular}{l*{5}{c}}" ///
"\midrule" ///
"&(1)&(2)&(3)&(4)&(5) \\" ///
"\midrule" ///
"a) Wage level & \multicolumn{4}{c}{Re-employment wage} \\ " ///
"\cmidrule(lr){2-4}" ///
"& \multicolumn{1}{c}{ln($ w $)}& & \multicolumn{1}{c}{ln($ w $)}& \multicolumn{1}{c}{$ \Delta $ ln($ w $)}   & \multicolumn{1}{c}{$ \Delta $ ln($ w $) } &\multicolumn{1}{c}{Pr($ EE $)} \\ " ///
"&&& $ EE=1 ,  t<\leq 6$ & \\\" ///
"\cmidrule(lr){2-4} \cmidrule(lr){5-5}") ///
postfoot("\bottomrule \end{tabular} \end{table}")
restore


eststo clear
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==12	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==24	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==36	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==48	 , cluster(varselid) fe nonest 

esttab , keep($instrument  _cons) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_wage_growth.tex", append prefoot() /// 
prehead("b) Wage growth & \multicolumn{4}{c}{Years since start of 1st employment} \\ " ///
"\cmidrule(lr){2-5}" ///
"& \multicolumn{1}{c}{ $ t+1 $ }& \multicolumn{1}{c}{ $ t+2 $} & \multicolumn{1}{c}{ $ t+3 $ } &\multicolumn{1}{c}{ $ t+4 $ } \\ " ///
"\addlinespace" ) ///
end("\\") begin("") keep(treat _cons)  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)  varlabels(treat "Above age-55" _cons "Control mean") ///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
postfoot("\bottomrule \end{tabular} \end{table}")

}
*
{ // RD graph: Wage AT FIRST NEW JOB graph 
*===============================================================================
preserve
	local lineopt 	"lpattern(dash) lcolor(black) lstyle(foreground)"
	local outcome 	"log_manl_newfirm2"		// switch between newfirm and newfirm2  for different wage meassures
	keep if nvals2==1 & eventtime_def<=24		// switch between nvals==1 and nvals2==1 for different wage meassures
	
	*winsor2 `outcome', c(1 99) replace
*=========
xtset ym_def
*=========

	*Main regression (1)
	xtreg `outcome'	$instrument $linear $covariets	 , cluster(varselid) fe nonest 
	local b = round(_b[$instrument] ,0.001)
	local se = round(_se[$instrument] ,0.001)
	keep if e(sample)==1
	gen freq=1
	
	*Residulize year*moth fixed effects
	xtreg `outcome'   $covariets  if e(sample)==1, cluster(varselid) fe nonest 
	predict e, e
	replace `outcome' = e  + _b[_cons]

	*Should be numerically equivelent to (1)
	xtreg `outcome' 	$instrument $linear 	 , cluster(varselid) fe nonest 
	
	*Fix bins of runvar
	gen 	bin = round(runvar*12)
	egen 	bin2 = cut(bin) , at(-36(2)1)
	egen 	bin3 = cut(bin), at(1(2)36)
	gen 	bin4 = bin2
	replace bin4 = bin3 if bin4==.
	replace bin4 = bin4 + 0.5
	bys bin4: egen `outcome'_bin = mean(`outcome')
	*tab  runvar bin4
	
	
	collapse (mean) `outcome' `outcome'_bin    (sum) freq , by(runvar bin4 treat)
	
	*Change scale of runvar
	replace runvar = runvar*12
	
	*Linear Fit
	twoway 	(scatter `outcome'_bin  bin4 		 	 , ms(o) mcolor(black))  		///	 	
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==0, lcolor(black)) 	 		///
		(lfit 	 `outcome' runvar [aweight=freq] 	if treat==1, lcolor(black))	 		///
		, xline(0 , `lineopt')  legend(off) graphregion(color(white)) 					///
		  xscale(r(-36 36)) xlabel(-36(12)36) 	 name(b,replace) 					///
		  xtitle("Normalized age (months)") ytitle("log(new wage)") ///
		  text(10.23 -9 "{&beta}=0`b'**" "(0`se')") yscale(r(10.16 10.26)) ylabel(10.16(.05)10.26)

	graph export "$agegraphpath/RD/RD_`outcome'_covars.pdf", replace
	graph export "$agegraphpath/RD/RD_`outcome'_covars.eps", replace as(eps)
restore	
}
*
{ // Wage distribtuion effect
*===============================================================================
preserve
xtset ym_def
keep if nvals==1 & eventtime_def<=24
sum diff_log_manl_newfirm,d
gen 	yvar = diff_log_manl_newfirm
replace yvar = -.2999999 if yvar<=-.3
replace yvar = .2999999 if yvar>=.3 & yvar!=.



matrix B = J(35,4,.)
foreach  x of numlist -.3 -.15 0 .15 {
	local i = `i' + 1
	gen dummy = inrange(yvar,`x',`x' + .1499999999)
	sum yvar if dummy==1,d
		 xtreg yvar	$instrument $linear $covariets 	if dummy==1	, cluster(varselid) fe nonest	
	
	matrix B[`i',1]  = `x' + .075
	matrix B[`i',2]  = _b[treat]
	matrix B[`i',3]  = _se[treat]
	matrix B[`i',4]  = e(df_r)
	drop dummy
}

svmat B
matrix list B
gen seu  = B2 + invttail(B4,0.025)*B3
gen sel = B2 - invttail(B4,0.025)*B3

sum yvar,d 
twoway 	(connected B2 B1 , yaxis(2) lcolor(black) mcolor(black) ms(o)) ///
	(rcap seu sel B1, lpattern(dash) lcolor(black) yaxis(2) )  ///
	(hist yvar, fraction width(.15) yaxis(1) start(-.3)  bcolor(navy%30) ) ///
	,yline(0,  axis(2) lpattern(dash) lcolor(black) lstyle(foreground) )  xscale(r(-.3 .3)) xlab(-.3 "{&le}-.3" -.15 0 .15  .3 ".3{&le}")  ///
	graphregion(color(white))  ytitle( "MN effect on Pr(Wage growth = x)", axis(2) ) xtitle("x") ytitle( "Pr(Wage growth = x)", axis(1)) ///
	legend(order(1 "MN effect on PDF" 3 "PDF (right axis)") ring(0) position(11)  col(1) size(vsmall))
	
	
graph export "$agegraphpath/Descriptive/wage_dist_effect.pdf",replace

drop B* seu sel yvar 
restore


}
*
{ // Wage table "summary stats"
*===============================================================================
xtset ym_def
preserve
keep if nvals==1 & eventtime_def<=24
eststo clear
eststo: xtreg log_manl_newfirm			$instrument $linear $covariets	 , cluster(varselid) fe nonest 
eststo: xtreg diff_log_manl_newfirm		$instrument $linear $covariets	 , cluster(varselid) fe nonest 
eststo: xtreg manl_newfirm			$instrument $linear $covariets	 , cluster(varselid) fe nonest 
eststo: xtreg manl_newfirm 	prenotfwage 	$instrument $linear $covariets	 , cluster(varselid) fe nonest 
eststo: xtreg prenotfwage			$instrument $linear $covariets	 , cluster(varselid) fe nonest 
eststo: xtreg log_prenotfwage			$instrument $linear $covariets	 , cluster(varselid) fe nonest 


esttab , keep($instrument _cons) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)
esttab using "$agetablepath/RF/tab_wage_summary.tex", 				/// 
replace keep($instrument _cons) booktabs nodepvars   				///
varlabels(treat "Above age-55" _cons "Control mean") se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
title("Wage effect of advance notice")	///
mlabels("ln($ w_1 $)" " $ \Delta $ ln($ w $) " "$ w_1 $" "$ w_1 \mid  w_0 $ " " $ w_0 $ "  "ln($ w_0 $) "  ) 					///
nonotes 
restore
}
*


log close


/*

{ // Table of new wage and wage growth (with EE interaction)
*===============================================================================
*============
xtset ym_def
*============
preserve
*Note: nvals==1 is what makes it the first wage observation at the first new firm
bys lopnr (date) : egen maxEtoE = max(EtoE)
gen EtoErunvar = maxEtoE*runvar
gen EtoEinter  = maxEtoE*inter 
gen EtoEtreat = maxEtoE*treat
keep if nvals==1 & eventtime_def<=24
eststo clear
qui eststo: xtreg log_manl_newfirm			$instrument $linear $covariets   , cluster(varselid) fe nonest 
qui eststo: xtreg diff_log_manl_newfirm 		$instrument $linear $covariets  , cluster(varselid) fe nonest 
qui eststo: xtreg diff_log_manl_newfirm 		$instrument $linear $covariets  if eventtime_def<=6 & EtoE==1, cluster(varselid) fe nonest 
qui eststo: xtreg diff_log_manl_newfirm 		$instrument $linear EtoEtreat EtoE EtoErunvar EtoEinter $covariets  , cluster(varselid) fe nonest 
qui eststo: xtreg EtoE					$instrument $linear $covariets 	 , cluster(varselid) fe nonest 


esttab , keep($instrument  EtoE* _cons) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) 	
esttab using "$agetablepath/RF/tab_wage_growth_incEtoE.tex", 				/// 
replace keep($instrument  EtoEtreat EtoE _cons) booktabs nodepvars  nomtitles nolines	nonumbers		///
varlabels(treat "Above age-55" _cons "Control mean" EtoEtreat "Above age-55 $ \times $ EE " EtoE "EE" ) se(3) b(3)  			///
star(* 0.1 ** 0.05 *** 0.01)   	substitute(\_ _)							///
title("Wage effect of advance notice")		///
stats( N_clust N, fmt( %9.0fc %9.0fc) 		/// 
labels( "\# clusters" "\# observations")) ///
nonotes postfoot("\addlinespace \midrule \addlinespace") prehead("\begin{table}[htbp]\centering" ///
"\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}" ///
"\caption{Wage effect of advance notice}" ///
"\begin{tabular}{l*{5}{c}}" ///
"\midrule" ///
"&(1)&(2)&(3)&(4)&(5) \\" ///
"\midrule" ///
"a) Wage level & \multicolumn{4}{c}{Re-employment wage} \\ " ///
"\cmidrule(lr){2-5}" ///
"& \multicolumn{1}{c}{ln($ w $)}& \multicolumn{1}{c}{$ \Delta $ ln($ w $)}   & \multicolumn{1}{c}{$ \Delta $ ln($ w $) } & \multicolumn{1}{c}{$ \Delta $ ln($ w $) } &\multicolumn{1}{c}{Pr($ EE $)} \\ " ///
"&&& $ EE=1 ,  t<\leq 6$ & & \\" ///
"\cmidrule(lr){2-5} \cmidrule(lr){6-6}")
restore


eststo clear
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==12	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==24	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==36	 , cluster(varselid) fe nonest 
qui eststo: xtreg wgrowth 	$instrument $linear $covariets  if timeafterjob==48	 , cluster(varselid) fe nonest 

esttab , keep($instrument  _cons) se(3) b(3) star(* 0.1 ** 0.05 *** 0.01) 
esttab using "$agetablepath/RF/tab_wage_growth_incEtoE.tex", append prefoot() /// 
prehead("b) Wage growth & \multicolumn{5}{c}{Years since start of 1st employment} \\ " ///
"\cmidrule(lr){2-6}" ///
"& \multicolumn{1}{c}{ $ t+1 $ }& \multicolumn{1}{c}{ $ t+2 $} & \multicolumn{1}{c}{ $ t+3 $ } &\multicolumn{1}{c}{ $ t+4 $ } \\ " ///
"\addlinespace" ) ///
end("\\") begin("") keep(treat _cons)  nonumbers nodepvar  nogaps nolines nomtitles ///
se(3) b(3) star(* 0.1 ** 0.05 *** 0.01)  varlabels(treat "Above age-55" _cons "Control mean") ///
stats( N_clust N, fmt( %9.0fc %9.0fc) /// 
labels( "\# clusters" "\# observations")) ///
postfoot("\bottomrule \end{tabular} \end{table}")

}
*


{ // Descriptive EE-gaph
*===============================================================================
preserve	
	*Condition on working at notifying firm at t=0
	gen xat1 =  atfirm2==1 if eventtime_def==0
	bys lopnr: egen at1 = max(xat1)
	keep if at1==1

	keep if within24months==1 & inrange(eventtime_def,0,24) 
	gcollapse (mean) leftfirm recall otherfirm2 EUE EtoE EU ,by(eventtime_def)
	
	gen EE= EUE + EtoE
	gen EU2 = EE + EU
	gen AF = 1-leftfirm 
	gen AF2 = 1- leftfirm + EU2
	gen RE = AF2 + recall
	
	gen temp =1-leftfirm
	gen tot = (1-leftfirm) + recall + EUE + EtoE + EU
	order temp recall EUE EtoE EU tot
	sum tot
	

	twoway (area  RE AF2 EU2 EE EUE   eventtime_def, acolor(maroon%20 maroon%40 navy%25 navy%50 navy)) , ///
	name(b,replace) graphregion(color(white)) yscale(r(0 1)) ylab(0(.2)1) ///
	legend(order(1 "Recalls" 2 "Notifying firm" 3 "EU" 4 "EE" 5 "EUE") col(3))
	graph export "$agegraphpath/Descriptive/EE_transitions_wagesample.pdf",replace
restore	
}
*
{ // Define globals
*===============================================================================
global covariets 	"C_annual_ear_prenot_def C_female C_immigrant C_tenureatnot C_educ1 C_educ2 C_educ3 "		
global instrument	"treat"
global linear		"runvar inter"
global quadratic	"$linear q_runvar q_inter"
global cubic 		"$quadratic c_runvar c_inter"
}
*
{ // Graph: all transitions
*===============================================================================
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

xtset ym_def
matrix Ball = J(25,10,.) 

*Seperate graphs of treatment and control estimates
preserve
	gen at = 1 - leftfirm
	*Condition on working at notifying firm at t=0
	gen xat1 =  atfirm2==1 if eventtime_def==0
	bys lopnr: egen at1 = max(xat1)
	keep if at1==1

	keep if within24months==1 & inrange(eventtime_def,0,24) 
	foreach var of varlist EtoE EUE EU at recall {
	local k = `k' + 1 
	local p = `k' + 5
		matrix B = J(25,4,.)
		local i = 0

		forvalues t = 0(1)24{
			local i = `i' + 1
			qui xtreg `var'		$instrument $linear $covariets 	if eventtime_def==`t' , cluster(varselid) fe nonest 

			matrix B[`i',1]  = `t'
			matrix B[`i',2]  = _b[_cons]
			matrix B[`i',3]  = _b[_cons] + _b[treat]
			matrix B[`i',4]  = abs(_b[treat]/_se[treat]) >invttail(e(df_r),0.025)
			matrix Ball[`i',`k'] =  _b[treat]
			matrix Ball[`i',`p'] =  _se[treat]
		}

		svmat B
		rename B1 t
		rename B2 C
		rename B3 T
		rename B4 sig

		*Graph


		twoway (connected T t, `Tstyle') (connected C t, `Cstyle') (rspike T C t if sig==1, `Sstyle') ///
		,xline(0, lstyle(foreground) lpattern(dash) lcolor(black)) xscale(r(0 24)) xlabel(-0(3)24)  ///
		xtitle("Months relative to notification") ytitle("Pr(`var')") name(`var',replace) ///
		graphregion(color(white)) legend(order( 1 "Long notification" 2 "Short notification" ) region(color(white)))
		graph export "$agegraphpath/Event/event_`var'_wagesample.pdf",replace

		drop t C T sig 
	}
restore

svmat Ball


*Combined graph of RD-estimates with CI's
preserve
	keep Ball1-Ball10
	keep in 1/25
	gen t = _n - 1
	
	gen seU_Ball1 = Ball1 + 1.96*Ball6
	gen seL_Ball1 = Ball1 - 1.96*Ball6
	gen seU_Ball2 = Ball2 + 1.96*Ball7
	gen seL_Ball2 = Ball2 - 1.96*Ball7
	gen seU_Ball3 = Ball3 + 1.96*Ball8
	gen seL_Ball3 = Ball3 - 1.96*Ball8
	gen seU_Ball4 = Ball4 + 1.96*Ball9
	gen seL_Ball4 = Ball4 - 1.96*Ball9
	
	twoway 	(connected Ball1 Ball2 Ball3 Ball4   t, mcolor(navy maroon dkgreen teal) lcolor(navy maroon dkgreen teal)) ///
		(rcap seU_Ball1 seL_Ball1 t ,lcolor(navy) lpattern(dash) lstyle(foreground) ) ///
		(rcap seU_Ball2 seL_Ball2 t ,lcolor(maroon) lpattern(dash) lstyle(foreground) ) ///
		(rcap seU_Ball3 seL_Ball3 t ,lcolor(dkgreen) lpattern(dash) lstyle(foreground)) ///
		(rcap seU_Ball4 seL_Ball4 t ,lcolor(teal) lpattern(dash) lstyle(foreground)) ///
	,legend(order(1 "EE" 2 "EUE" 3 "EU" 4 "At firm" ) col(4)) ///
	graphregion(color(white))
	graph export "$agegraphpath/Event/event_EEtrans_wagesample.pdf",replace
restore

drop Ball*

}
*
{ // Graph: RD stack 
*===============================================================================
local Tstyle "ms(o) mcolor(black) lcolor(black) lpattern(solid)"
local Cstyle "ms(oh) mcolor(black) lcolor(black) lpattern(dash)"
local Sstyle "lpattern(shortdash_dot) lcolor(gray) vertical" 

xtset ym_def
matrix Ball = J(25,10,.) 

*Seperate graphs of treatment and control estimates
preserve
	keep if within24months==1
	gen at = 1 - leftfirm
	*Condition on working at notifying firm at t=0
	gen xat1 =  atfirm2==1 if eventtime_def==0
	bys lopnr: egen at1 = max(xat1)
	keep if at1==1

	keep if  inrange(eventtime_def,0,24) 
	gen EE_EUE = (EtoE==1 | EUE==1)
	gen EE_EUE_EU = (EtoE==1 | EUE==1 | EU==1)
	
	local k=0
	local p=0
	local q=0
	
	foreach var of varlist EtoE EE_EUE EE_EUE_EU{
	local k = `k' + 1 
	local p = `k' + 3
	local q = `k' + 6
		matrix B = J(25,4,.)
		local i = 0

		forvalues t = 0(1)24{
			local i = `i' + 1
			qui xtreg `var'		$instrument $linear $covariets 	if eventtime_def==`t' , cluster(varselid) fe nonest 

			matrix B[`i',1]  = `t'
			matrix B[`i',2]  = _b[_cons]
			matrix B[`i',3]  = _b[_cons] + _b[treat]
			matrix B[`i',4]  = abs(_b[treat]/_se[treat]) >invttail(e(df_r),0.025)
			matrix Ball[`i',`k'] =  _b[treat]
			matrix Ball[`i',`p'] =  _b[_cons]
			matrix Ball[`i',`q'] = abs(_b[treat]/_se[treat]) >invttail(e(df_r),0.025)
		}

		svmat B
		rename B1 t
		rename B2 C
		rename B3 T
		rename B4 sig

		*Graph


		twoway (connected T t, `Tstyle') (connected C t, `Cstyle') (rspike T C t if sig==1, `Sstyle') ///
		,xline(0, lstyle(foreground) lpattern(dash) lcolor(black)) xscale(r(0 24)) xlabel(-0(3)24)  ///
		xtitle("Months relative to notification") ytitle("Pr(`var')") name(`var',replace) ///
		graphregion(color(white)) legend(order( 1 "Long notification" 2 "Short notification" ) region(color(white)))
		graph export "$agegraphpath/Event/event_`var'_wagesample.pdf",replace

		drop t C T sig 
	}
restore

matrix list Ball
svmat Ball


*Combined graph of RD-estimates with CI's
preserve
	keep Ball1-Ball9
	keep in 1/25
	gen t = _n - 1
	
	rename Ball1	T_EE
	rename Ball2	T_EE_EUE
	rename Ball3	T_EE_EUE_EU
	rename Ball4	C_EE
	rename Ball5	C_EE_EUE
	rename Ball6	C_EE_EUE_EU
	rename Ball7	S_EE
	rename Ball8	S_EE_EUE
	rename Ball9	S_EE_EUE_EU
	
	
	gen  F1 = C_EE + T_EE
	gen  F2 = C_EE_EUE + T_EE_EUE
	gen  F3 = C_EE_EUE_EU + T_EE_EUE_EU
	
	twoway 	(connected F1 C_EE F2 C_EE_EUE F3  C_EE_EUE_EU t , ///
	mcolor(black black black black black black) ///
	ms(o oh T Th S Sh ) ///
	lpattern(solid dash solid dash solid dash) ///
	lcolor(black black black black black black)) ///
	(rspike F1 C_EE 	t if S_EE==1, lpattern(shortdash_dot) lcolor(gray) vertical) ///
	(rspike F2 C_EE_EUE 	t if S_EE_EUE==1, lpattern(shortdash_dot) lcolor(gray) vertical) ///
	(rspike F3 C_EE_EUE_EU 	t if S_EE_EUE_EU==1, lpattern(shortdash_dot) lcolor(gray) vertical) ///
	,legend(off) ///
	text(.2 15 "EE", place(e) color(black)) ///
	text(.8 20 "EUE", place(e) color(black)) ///
	text(.8 12 "Non-employment", place(e) color(black) angle(25)) ///
	text(.8 2 "At notifying firm", place(e) color(black)) ///
	graphregion(color(white)) xtitle("Months relative to notification") ytitle("Cumulative share")
	
	graph export "$agegraphpath/Event/event_RDstack_EEtrans_wagesample.pdf",replace
restore

drop Ball*

}
*
